package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.constant.MessageConstant;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Menu;
import com.itheima.health.service.MenuService;
import com.itheima.health.utils.QiNiuUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/menu")
public class MenuController {
    private Logger log = LoggerFactory.getLogger(MenuController.class);
    @Reference
    private MenuService menuService;

    @GetMapping("/findMenuList")
    public Result findMenuList(String username) {
        List<Menu> menuList = menuService.findMenuList(username);
        return new Result(true, MessageConstant.GET_MENU_LIST_SUCCESS, menuList);
    }

    @PostMapping("/findPage")
    public Result findByPage(@RequestBody QueryPageBean queryPageBean) {
        // 调用服务 分页查询
        PageResult<Menu> pageResult = menuService.findPage(queryPageBean);
        return new Result(true, MessageConstant.QUERY_CHECKITEM_SUCCESS, pageResult);
    }

    /**
     * 查询所有主菜单
     *
     * @return
     */
    @GetMapping("/findMainAll")
    public Result findMainAll() {
        List<Menu> menuList = menuService.findMainAll();
        return new Result(true, "查询主菜单成功", menuList);
    }

    //接收查询所有菜单的请求方法
    @RequestMapping("/findAll")
    public Result findMenu() {
        try {
            //调用service查询菜单数据
            List<Menu> menuList = menuService.findAll();
            //响应数据给客户端；
            return new Result(true, MessageConstant.QUERY_MENU_SUCCESS, menuList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_MENU_FAIL);
        }
    }

    @RequestMapping("/add")
    public Result menuAdd(@RequestBody Menu menu) {
        try {
            //  传入数据：菜单数据，角色id,角色id使用get方式：/add?id=
            //接收添加菜单表单数据，调用service处理添加请求
            menuService.add(menu);
            return new Result(true, MessageConstant.ADD_MENU_SUCCESS);
        } catch (RuntimeException r) {
            r.printStackTrace();
            return new Result(false, "已有相同菜单，勿重复添加");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_MENU_FAIL);
        }
    }

    @RequestMapping("/deleteById")
    public Result deleteById(Integer menuId) {
        try {
            //controller接收请求，接收参数Interger类型id，调用service层处理删除请求，传入菜单id
            menuService.deleteById(menuId);
            return new Result(true, MessageConstant.DELETE_MENU_SUCCESS);
        } catch (RuntimeException r) {
            r.printStackTrace();
            return new Result(false, "该菜单已有角色使用，请解除关联后再试！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.DELETE_MENU_SUCCESS);
        }
    }

    @PostMapping("/update")
    public Result update(@RequestBody Menu menu) {
        try {
            //调用service处理修改请求
            menuService.update(menu);
            return new Result(true, MessageConstant.EDIT_MENU_SUCCESS);
        } catch (RuntimeException r) {
            r.printStackTrace();
            return new Result(false, "有关联的角色，无法修改");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_MENU_FAIL);
        }
    }

    /*编辑：传入菜单id，回显菜单数据*/
    @RequestMapping("/findById")
    public Result findMenuById(Integer id) {
        try {
            //调用service处理回显请求
            Menu menu = menuService.findMenuById(id);
            //响应菜单数据，和是否成功
            return new Result(true, MessageConstant.QUERY_MENU_SUCCESS, menu);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_MENU_FAIL);
        }
    }

    /**
     * 上传图片
     *
     * @param imgFile
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile imgFile) {
        //1. 获取源文件名
        String originalFilename = imgFile.getOriginalFilename();
        //2. 截取后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //3. 生成唯一id,
        String uniqueId = UUID.randomUUID().toString();
        //4. 拼接唯一文件名
        String filename = uniqueId + suffix;
        //5. 调用7牛工具上传图片
        try {
            QiNiuUtils.uploadViaByte(imgFile.getBytes(), filename);
            //6. 构建返回的数据
            /*
             {
                imgName: 图片名 , 补全formData.img
                domain: 七牛的域名 图片回显imageUrl = domain+图片名
            }
             */
            Map<String, String> map = new HashMap<String, String>(2);
            map.put("imgName", filename);
            map.put("domain", QiNiuUtils.DOMAIN);
            //7. 放到result里，再返回给页面
            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, map);
        } catch (IOException e) {
            log.error("上传文件失败了", e);
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
    }
}
